package zj.com.activities;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.xutils.DbManager;
import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import zj.com.adapter.DjcAdapter;
import zj.com.adapter.DzgAdapter;
import zj.com.app.ZjApplication;
import zj.com.db.DBUtil;
import zj.com.model.DjcModel;
import zj.com.model.Dzg;
import zj.com.model.DzgDetail;
import zj.com.model.DzgDetailDB;
import zj.com.model.DzgInspectItemDB;
import zj.com.model.JcdInfoDB;
import zj.com.model.JcxDB;
import zj.com.model.UploadFile;
import zj.com.net.NetManager;
import zj.com.net.OnResponseListener;
import zj.com.util.DialogUtil;
import zj.com.util.LogUtils;
import zj.com.zj.R;

/**
 * Created by xi on 16/6/3.
 * 待整改
 */
public class DzgListActivity extends  BaseActivity implements View.OnClickListener{


    public TextView title_name;
    public ImageView left_iv;
    public TextView right_tv,cancel_tv,submit_tv,del_tv;
    public ImageView right_iv;
    public ListView listView;
    public List<Dzg> list;
    public DzgAdapter adapter;
    public Intent intent;

    public LinearLayout bottom_ll;
    private ProgressDialog dialog;
    public RelativeLayout error_rl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dzg_list);

        initView();
        initData();
    }

    public void initView(){

        error_rl = (RelativeLayout) findViewById(R.id.error_rl);
        cancel_tv = (TextView) findViewById(R.id.cancel_tv);
        cancel_tv.setOnClickListener(this);
        bottom_ll = (LinearLayout) findViewById(R.id.bottom_ll);
        submit_tv = (TextView) findViewById(R.id.submit_tv);
        submit_tv.setOnClickListener(this);

        del_tv  = (TextView) findViewById(R.id.del_tv);
        del_tv.setOnClickListener(this);

        left_iv = (ImageView) findViewById(R.id.left_iv);
        left_iv.setVisibility(View.VISIBLE);
        left_iv.setOnClickListener(this);
        title_name = (TextView) findViewById(R.id.title_name);
        right_tv = (TextView) findViewById(R.id.right_tv);
        right_tv.setVisibility(View.VISIBLE);
        right_tv.setOnClickListener(this);
        right_tv.setText("编辑");
        right_tv.setVisibility(View.VISIBLE);
        title_name.setText("待整改任务");

        right_iv = (ImageView) findViewById(R.id.right_iv);
        right_iv.setVisibility(View.GONE);
        right_iv.setImageResource(R.drawable.edit_icon);
        right_iv.setOnClickListener(this);


        listView = (ListView) findViewById(R.id.listView);


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                intent = new Intent(DzgListActivity.this,DzgDetailActivity.class);
                ZjApplication.dzgDetailDB = null;
                intent.putExtra("detail",list.get(position));
                startActivity(intent);
            }
        });

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                bottom_ll.setVisibility(View.VISIBLE);
                right_tv.setVisibility(View.GONE);
                adapter.setIsEdit(true);
                adapter.setSelect(position);
                return false;
            }
        });
    }

    public void initData(){

        list = new ArrayList<>();
        adapter = new DzgAdapter(list,this);
        listView.setAdapter(adapter);

    }

    @Override
    protected void onResume() {
        super.onResume();
        obtainData();

    }

    public void obtainData(){
        dialog = DialogUtil.createProgressDialog(this,"提示","获取数据中....");
        NetManager.getInstance(this).obtainGetToBeRepairedInspectionList(new OnResponseListener<List<Dzg>>() {
            @Override
            public void onComplete(boolean isOK, List<Dzg> result, int errorCode, String errorMsg) {

                dialog.dismiss();
                if (isOK) {

                    list = result;
                    if (list != null && list.size() > 0) {
                        right_tv.setVisibility(View.VISIBLE);
                        error_rl.setVisibility(View.GONE);
                    } else {
                        right_tv.setVisibility(View.GONE);
                        error_rl.setVisibility(View.VISIBLE);

                    }
                    adapter.setDataChange(list);
                } else {
                    error_rl.setVisibility(View.VISIBLE);
                    Toast.makeText(DzgListActivity.this, "获取失败", Toast.LENGTH_SHORT).show();

                }
            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {
                dialog.dismiss();
                Toast.makeText(DzgListActivity.this, "获取失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.left_iv:
                finish();
                break;
            case R.id.right_iv:

                break;
            case R.id.cancel_tv:
                bottom_ll.setVisibility(View.GONE);
                right_tv.setVisibility(View.VISIBLE);
                adapter.setIsEdit(false);
                adapter.getSelectMap().clear();
                adapter.notifyDataSetChanged();
                adapter.setSelect(-1);
                break;
            case R.id.submit_tv:
                bottom_ll.setVisibility(View.GONE);
                right_tv.setVisibility(View.VISIBLE);
                adapter.setIsEdit(false);
                upload();
                break;

            case R.id.right_tv:
                bottom_ll.setVisibility(View.VISIBLE);
                right_tv.setVisibility(View.GONE);
                adapter.setIsEdit(true);

                break;
            case R.id.del_tv:
                bottom_ll.setVisibility(View.GONE);
                right_tv.setVisibility(View.VISIBLE);
                adapter.setIsEdit(false);
                break;

        }

    }

    public void upload(){
        DbManager dbManager = DBUtil.getInstance(this).getDBManager();

        Map<Integer, Boolean> selectMap = adapter.getSelectMap();
        for (Map.Entry<Integer, Boolean> entry : selectMap.entrySet()) {


            Dzg dzg  =  list.get(entry.getKey());

            try {
                DzgDetailDB detail = dbManager.selector(DzgDetailDB.class).where("inspection_id", "=", dzg.getInspectionID()).where("inspectionitem_id", "=", dzg.getInspectItemID()).findFirst();
                if(detail != null){

                    List<DzgInspectItemDB> items =  dbManager.selector(DzgInspectItemDB.class).where("inspectid", "=", dzg.getInspectionID()).findAll();
                    if(items.size() == detail.getInpsect_count() && items.size() > 0){
                        uploadImg(dzg,detail);

                        LogUtils.getInstance().error("wxf",entry.getKey()+"   test=======");
                    }else{
                        Toast.makeText(DzgListActivity.this, "你提交的任务有未完善的信息，请完善再提交", Toast.LENGTH_SHORT).show();
                    }

                    LogUtils.getInstance().error(detail.getInpsect_count()+"......");
                }else{
                    Toast.makeText(DzgListActivity.this, "你提交的任务有未完善的信息，请完善再提交", Toast.LENGTH_SHORT).show();
                }
            }catch(Exception e){

            }

        }



    }

    public int count = 0;
    public void uploadImg(final Dzg d,final DzgDetailDB dzg){


        count = 0;
        try{
            final DbManager dbManager = DBUtil.getInstance(this).getDBManager();
           final List<DzgInspectItemDB> items =  dbManager.selector(DzgInspectItemDB.class).where("inspectionitem_id", "=", dzg.getInspectionItemID()).findAll();

            if(items != null){
                dialog = DialogUtil.createProgressDialog(this,"提示","上传图片中..");
                for(final DzgInspectItemDB item:items){
                    String img =  item.getImgs();
                    NetManager.getInstance(this).newUploadImg(img, new OnResponseListener<List<UploadFile>>() {
                        @Override
                        public void onComplete(boolean isOK, List<UploadFile> result, int errorCode, String errorMsg) {

                            if(isOK){

                                dialog.setMessage("上传数据中...");
                                StringBuffer sb = new StringBuffer();
                                for(UploadFile file:result){
                                    sb.append(file.getResourceId());
                                    sb.append(",");
                                }
                                item.setUploadImgs(sb.toString());
                                try {
                                    dbManager.saveOrUpdate(item);
                                } catch (DbException e) {
                                    e.printStackTrace();
                                }

                                count ++;
                                if(count == items.size()){
                                    doSumbitData(d,dzg);
                                    LogUtils.getInstance().error("count ====="+count);
                                }

                            }else{
                                dialog.dismiss();
                                Toast.makeText(DzgListActivity.this, " 上传失败", Toast.LENGTH_SHORT).show();

                            }
                        }

                        @Override
                        public void onInternError(int errorCode, String errorMessage) {
                            dialog.dismiss();

                            Toast.makeText(DzgListActivity.this, " 上传失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }else{

                Toast.makeText(DzgListActivity.this, "请填写相应的整改项内容", Toast.LENGTH_SHORT).show();
            }
        }catch (Exception e){

        }


    }

    public void doSumbitData(final Dzg d,final DzgDetailDB dzg){

        NetManager.getInstance(this).AddRepairRecord(d, new OnResponseListener<Dzg>() {
            @Override
            public void onComplete(boolean isOK, Dzg result, int errorCode, String errorMsg) {


                if(isOK){
                    dialog.dismiss();

                    DbManager dbManager = DBUtil.getInstance(DzgListActivity.this).getDBManager();
                    try {
                        DzgDetailDB detail =  dbManager.selector(DzgDetailDB.class).where("inspection_id", "=", dzg.getInspectionID() + "").where("inspectionitem_id", "=", dzg.getInspectionItemID()).findFirst();
                        if(detail != null){
                            dbManager.delete(detail);

                        }
                        List<DzgInspectItemDB> items =  dbManager.selector(DzgInspectItemDB.class).where("inspectionitem_id", "=", dzg.getInspectionItemID()).findAll();
                        if(items != null){
                            for(DzgInspectItemDB item:items){
                                dbManager.delete(item);
                            }

                        }
                    } catch (DbException e) {
                        e.printStackTrace();
                    }

                    obtainData();
                    ZjApplication.dzgInspectItemDB = null;
                    ZjApplication.dzgDetailDB = null;
                    Toast.makeText(DzgListActivity.this, " 提交成功", Toast.LENGTH_SHORT).show();


                }else{
                    dialog.dismiss();
                    Toast.makeText(DzgListActivity.this, " 提交失败", Toast.LENGTH_SHORT).show();

                }
            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {
                dialog.dismiss();

                Toast.makeText(DzgListActivity.this, " 提交失败", Toast.LENGTH_SHORT).show();

            }
        });
    }

}
